﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using Orchard.ContentManagement;
using Orchard.ContentManagement.Handlers;
using Orchard.Data;
using SchoolPointe.Menus.Models;
using SchoolPointe.RelatedContent.Services;
using SchoolPointe.RelatedContent.Models;
using Orchard.Environment.Extensions;
using Orchard.Core.Navigation.Models;

namespace SchoolPointe.Menus.Handlers
{
    //I am overriding the built-in handler because it provided the menu item URL as an identity specifier, and it would blow up on empty URLs
    [OrchardSuppressDependency("Orchard.Core.Navigation.Handlers.MenuItemPartHandler")]
    public class BetterMenuItemHandler : ContentHandler
    {
        private readonly IRelatedContentService _relatedContentService;
        private readonly IContentManager _contentManager;

        public BetterMenuItemHandler(
            IRepository<BetterMenuItemPartRecord> repository, 
            IRelatedContentService relatedContentService, 
            IContentManager contentManager, 
            IRepository<MenuItemPartRecord> menuItemRepo)
        {
            Filters.Add(new ActivatingFilter<MenuItemPart>("MenuItem"));
            Filters.Add(StorageFilter.For(menuItemRepo));   
     
            _relatedContentService = relatedContentService;
            _contentManager = contentManager;

            Filters.Add(StorageFilter.For(repository));
            OnInitializing<BetterMenuItemPart>(LazyLoadHandlers);
        }

        protected override void GetItemMetadata(GetContentItemMetadataContext context)
        {
        }

        private void LazyLoadHandlers(InitializingContentContext context, BetterMenuItemPart part)
        {
            part.RelatedItem.Loader(() =>
            {
                var ciRecord = _relatedContentService.GetRelatedItems(part.As<RelatedContentPart>(), "menu-content").FirstOrDefault();
                if (ciRecord == null) return null;
                return _contentManager.Get(ciRecord.Id);
            });
        }
    }
}
